public class Solution {
    public String longestCommonPrefix(String[] strs) {
        int len = strs.length;
        String ret = strs[0];
        for (String str : strs) {
            ret = method(ret, str);
        }
        return ret;
    }

    public String method(String str1, String str2) {//寻找两个字符串的最长公共前缀
        StringBuilder ret = new StringBuilder();
        int len1 = str1.length();
        int len2 = str2.length();
        for (int i = 0; i < len1 && i < len2; i++) {
            if (str1.charAt(i) == str2.charAt(i)) {
                ret.append(str1.charAt(i));
            } else {
                break;
            }
        }
        return ret.toString();
    }

    public String longestCommonPrefix2(String[] strs) {//一次比较所有前缀
        int len = strs[0].length();
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < len; i++) {
            char ch = strs[0].charAt(i);
            // boolean flag = true;
            for (String str : strs) {
                if (i >= str.length() || ch != str.charAt(i)) {
                    return ret.toString();
                }
            }
            ret.append(ch);
        }
        return ret.toString();
    }
}
